"""
通过浏览器复用的方式 , 解决懂车帝登录总是提示使用验证码登录的问题 .

在运行代码之前 , 需要保证已经启动了复用浏览器 :
    chrome --remote-debugging-port=9222
"""
import os
from time import sleep

from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.support import expected_conditions as e_c
from selenium.webdriver.support.wait import WebDriverWait


def options():
    option = Options()
    option.debugger_address = 'localhost:9222'
    return option


class BasePage:

    def __init__(self, driver: webdriver.Chrome = None):
        if not driver:
            # os.system('chrome --remote-debugging-port=9222')
            # sleep(10)
            self.driver = webdriver.Chrome(options=options())
            self.driver.implicitly_wait(2)
            self.wait = WebDriverWait(self.driver, 2)
        else:
            self.driver = driver

    @staticmethod
    def sleep(seconds):
        sleep(seconds)

    def find_ele(self, locator: tuple):
        ele = self.driver.find_element(*locator)
        return ele

    def find_ele_visibility(self, locator: tuple):
        self.wait.until(e_c.visibility_of_element_located(locator))
        ele = self.driver.find_element(*locator)
        return ele

    def click_visibility_by_locator(self, locator: tuple):
        ele = self.find_ele_visibility(locator)
        ele.click()

    def save_screenshot(self, file_name):
        self.driver.save_screenshot(file_name)

    def close(self):
        sleep(2)
        self.driver.close()
        sleep(2)
        self.driver.quit()
